package io.github.wppli.domain.recommond.rservice;

import cc.jq1024.middleware.redisson.IRedissonService;
import io.github.wppli.domain.recommond.model.entity.ContentFeatureEntity;
import io.github.wppli.domain.recommond.repository.IContentFeatureRepository;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @author li--jiaqiang 2025−03−16
 */
@Service
@AllArgsConstructor
public class ContentFeatureService implements IContentFeatureService {

    private final IContentFeatureRepository featureRepository;
    private final IRedissonService redissonService;

    @Override
    public List<ContentFeatureEntity> findByContentIds(List<Long> contentIds) {
        String key = "content_feature_contentIds_" + contentIds;
        List<ContentFeatureEntity> contentFeatureEntities = redissonService.getList(key, ContentFeatureEntity.class);
        if (contentFeatureEntities == null || contentFeatureEntities.isEmpty()) {
            contentFeatureEntities = featureRepository.findByContentIds(contentIds);
            redissonService.setValue(key, contentFeatureEntities, 60 + new Random().nextInt(20), TimeUnit.MINUTES);
        }
        return contentFeatureEntities;
    }

    @Override
    public List<ContentFeatureEntity> findAll() {
        String key = "content_feature_all_ContentFeatureEntity";
        List<ContentFeatureEntity> contentFeatureEntities = redissonService.getList(key, ContentFeatureEntity.class);
        if (contentFeatureEntities == null || contentFeatureEntities.isEmpty()) {
            contentFeatureEntities = featureRepository.findAll();
            redissonService.setValue(key, contentFeatureEntities, 60 + new Random().nextInt(20), TimeUnit.MINUTES);
        }
        return contentFeatureEntities;
    }

    @Override
    public void save(Long contentId, String json) {
        featureRepository.save(contentId, json);
    }
}